package com.itheima.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/download/*")
public class DownloadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setCharacterEncoding("utf-8");
//        1. 获取请求提交的要下载的文件名
        String filename = request.getParameter("filename");
//        2. 创建输入流指向于 `D:\\download\\` 下的指定的文件
        FileInputStream fileInputStream=new FileInputStream("D:\\download\\" + filename);
//        3. 设置 `Content-Disposition` 响应头 。如： `resp.setHeader("Content-Disposition","attachment;filename=mysql-5.7.24-winx64.zip");`
        response.setHeader("Content-Disposition","attachment;filename=mysql-5.7.24-winx64.zip");
//        4. 通过response对象获取输出流对象
        ServletOutputStream out =response.getOutputStream();
//        5. 读写数据
        int ff=-1;
        while ((ff = fileInputStream.read()) != -1){
            out.write(ff);
        }
//        6. 释放资源
        fileInputStream.close();
    }
}